# coding: utf-8

from leancloud import Object
from leancloud import File
from leancloud import Query
from leancloud import LeanCloudError
from leancloud import User
from flask import request
from datetime import datetime
import time
import os
from werkzeug.utils import secure_filename
import json

class FarmerSayItem(Object):
    pass

class MFollowee(Object):
    pass


class MFollower(Object):
    pass


class FolloweeSay():
       # 添加关注
    def addFollowee(self):
        username = request.json['user']
        followee = request.json['followee']
        try:
            mFollowees = Query(MFollowee).equal_to("user", username).equal_to("followee", followee).descending(
                    'createdAt').find()
            count = len(mFollowees)
            if (count > 0):
                data = {'code': 200, 'result': "already follow"}
            else:
                mFollowee = MFollowee()
                mFollowee.set("user", username)
                mFollowee.set("followee", followee)
                mFollowee.save()
                mFollower = MFollower()
                mFollower.set("user", followee)
                mFollower.set("follower", username)
                mFollower.save()
                data = {'code': 200, 'result': "success"}
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                data = {'code': 101, 'result': e}
                pass
            else:
                data = {'code': 100, 'result': e}
                raise e
        return json.dumps(data, indent=1)
        pass

    def cancelFollowee(self):
        username = request.json['user']
        followee = request.json['followee']
        try:
            mFollowees = Query(MFollowee).equal_to("user", username).equal_to("followee", followee).descending(
                    'createdAt').find()
            for mFollowee in mFollowees:
                mFollowee.destroy()
            mFollowers = Query(MFollower).equal_to("user", followee).equal_to("follower", username).descending(
                    'createdAt').find()
            for mFollower in mFollowers:
                mFollower.destroy()
            data = {'code': 200, 'result': "success"}
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                data = {'code': 101, 'result': e}
                pass
            else:
                data = {'code': 100, 'result': e}
                raise e
        return json.dumps(data, indent=1)
        pass